package org.aisino.shdzfp.vistool.util;

import java.io.IOException;
import java.io.StringWriter;

import org.aisino.shdzfp.vistool.exception.NullXmlException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class XmlFormatUtil {

	private static String formatXml(String str) throws DocumentException, IOException {
		Document document = null;
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		try(StringWriter writer = new StringWriter()) {
			document = DocumentHelper.parseText(str);
			// 格式化输出格式
			// 格式化输出流
			XMLWriter xmlWriter = new XMLWriter(writer, format);
			// 将document写入到输出流
			xmlWriter.write(document);
			xmlWriter.close();
			return writer.toString();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * 预处理
	 * 
	 * @param xml
	 * @return
	 * @throws NullXmlException
	 */
	private static String preFormat(String xml) throws NullXmlException {
		if (xml == null) {
			throw new NullXmlException();
		} else {
			return xml.trim().replaceAll(">\\s+<", "><");
		}
	}
	
	public static void main(String[] args) throws NullXmlException {
		String s = "> < > *<";
		System.out.println(preFormat(s));
	}
	
	public static String format(String xml) throws NullXmlException, DocumentException, IOException {
		return formatXml(preFormat(xml));
	}
	
	public static String[] getMeta(String xml) throws NullXmlException {
		if(xml == null) {
			throw new NullXmlException();
		} else {
			return xml.trim().split("\n");
		}
	}
}
